package com.enjoyor.soa.traffic.server.efoms.dubbo.listener;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import java.io.ByteArrayOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.util.UriUtils;

import com.enjoyor.soa.traffic.api.dto.idcs.VehiclePassDto;
import com.enjoyor.soa.traffic.core.efoms.domain.DeviceDetailInfo;
import com.enjoyor.soa.traffic.core.efoms.domain.DeviceStatusInfo;
import com.enjoyor.soa.traffic.core.efoms.enums.EnumDicPublic;
import com.enjoyor.soa.traffic.core.efoms.service.IDevStatusInfoService;
import com.enjoyor.soa.traffic.core.efoms.service.IDeviceDetailInfoService;
import com.enjoyor.soa.traffic.server.efoms.common.Global;
import com.enjoyor.soa.traffic.server.efoms.dubbo.invoke.DubboSolrClientInvoke;
import com.enjoyor.soa.traffic.server.efoms.helper.FTPAllFilesHelper;
import com.enjoyor.soa.traffic.util.helper.TimeHelper;

/**
 *
 * 定时获取视频截图路径
 * @Description TODO
 * @Author fzj
 * @Date 2019/5/1 9:41
 * @Version 1.0
 **/
@Component
public class ScheduledVideoCapService {

	@Autowired
    private IDevStatusInfoService devStatusInfoService;
    @Autowired
    private IDeviceDetailInfoService deviceDetailInfoService;
    
	@Autowired
    private DubboSolrClientInvoke solrClientInvoke;
	
	//默认操作人
	String personName = "同步视频截图";

    @Value("${bayonet.pic.issyn}")
    private String bayonetPicIssyn;
    
    @Value("${video.cap.issyn}")
    private String videoCapIssyn;
    @Value("${ftp.upload.ip}")
    private String ftpIp;
	@Value("${ftp.upload.port}")
    private String ftpPort;
	@Value("${ftp.upload.user}")
    private String ftpUser;
	@Value("${ftp.upload.password}")
    private String ftpPassword;

    /**
     * 定时获取视频截图路径
     */
	//@Scheduled(cron="0 */5 * * * ?")
	@Scheduled(cron="0 0 ${video.cap.syn.period} * * ?")
    public void getLedStatusScheduled(){
    	if(!"1".equals(videoCapIssyn)) return;
    	FTPAllFilesHelper ftpFilesHelper = new FTPAllFilesHelper(true);
        List<String> arFiles = new ArrayList<String>();
        String dirName = TimeHelper.dateToString(TimeHelper.addDate(new Date(), -1), "yyyyMMdd");
        //String dirName = TimeHelper.dateToString(new Date(), "yyyyMMdd");
        try {
        	if (ftpFilesHelper.login(ftpIp, Integer.parseInt(ftpPort), ftpUser, ftpPassword)) {
            	arFiles = ftpFilesHelper.ListFiles("/"+dirName+"/");
            }
			ftpFilesHelper.disConnection();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        if(arFiles.size() > 0) {
        	//获取所有视频监测基础数据
        	List<DeviceDetailInfo> videoInfoList = deviceDetailInfoService.selectDeviceDetailInfoList(
        			EnumDicPublic.VIDEO.getKey(), null, null, null, null, null, null);
        	if(null != videoInfoList && videoInfoList.size() > 0 ) {
        		for(DeviceDetailInfo videoInfo : videoInfoList) {
        			Boolean flag  = false;
        			String videoCapUrl = "-";
        			for (String arFile : arFiles) {
        				String fileId = arFile.split("\\.")[0];
        				if(fileId.equals(videoInfo.getVideoPlayId())) {
            				videoCapUrl = "ftp://" + ftpUser + ":" + ftpPassword + "@" + ftpIp + ":" + ftpPort 
            						+ "//" + dirName + "//" + arFile;
            				flag  = true;
            				break;
            			}
        			}

					String key = EnumDicPublic.VIDEO.getKey() + "-" + videoInfo.getDevId();
					DeviceStatusInfo deviceStatusPool = Global.DevStatusPool.get(key);
					//更新设备状态表以及对应内存
					if(null == deviceStatusPool) { 
						DeviceStatusInfo deviceStatusInfo = new DeviceStatusInfo();
	        			deviceStatusInfo.setDevCategoryCode(EnumDicPublic.DEV_CATEGORY.getKey());
	        			deviceStatusInfo.setDevCategoryName(EnumDicPublic.DEV_CATEGORY.getValue());
	        			deviceStatusInfo.setDevTypeCode(EnumDicPublic.VIDEO.getKey());
	        			deviceStatusInfo.setDevTypeName(EnumDicPublic.VIDEO.getValue());
	        			deviceStatusInfo.setDevId(videoInfo.getDevId());
	        			deviceStatusInfo.setDevName(videoInfo.getDevName());
	        			deviceStatusInfo.setIsPhotoSuccess(flag);
	        			deviceStatusInfo.setVideoCapUrl(videoCapUrl);
	        			devStatusInfoService.insertDevStatusInfo(deviceStatusInfo, personName);
						Global.DevStatusPool.put(key, deviceStatusInfo);
					}else if(flag != deviceStatusPool.getIsPhotoSuccess()||!videoCapUrl.equals(deviceStatusPool.getVideoCapUrl())) {
						deviceStatusPool.setIsPhotoSuccess(flag);
						deviceStatusPool.setVideoCapUrl(videoCapUrl);
						devStatusInfoService.updateDevStatusInfo(deviceStatusPool, personName);
						Global.DevStatusPool.put(key, deviceStatusPool);
					}
        		}
        	}
        }else {
        	//没有获取到任何文件，清空视频截图路径
        	String devTypeCode = EnumDicPublic.VIDEO.getKey();
        	devStatusInfoService.cleanVideoCapStatus(devTypeCode);
        }
    }
    
    /**
    * 功能：检测当前URL是否可连接或是否有效,
    * 描述：最多连接网络 5 次, 如果 5 次都不成功，视为该地址不可用
    * @param urlStr 指定URL网络地址
    * @return URL
    */
	public static Boolean isConnect(String urlStr) {
		int counts = 0;
		Boolean flag = false;
		if (urlStr == null || urlStr.length() <= 0) {
			return flag;
		}
		while (counts < 5) {
			try {
				URL url = new URL(urlStr);
				HttpURLConnection con = (HttpURLConnection) url.openConnection();
				int state = con.getResponseCode();
				//System.out.println(counts + "= " + state);
				if (state == 200) {
					flag = true;
					break;
				}
				counts++;
			} catch (Exception ex) {
				counts++;
				continue;
			}
		}
		return flag;
	}
}
